package net.livingflow.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.livingflow.model.Flow;

import org.springframework.stereotype.Service;

/**
 * @author xueqiang.mi
 * @since 2010-11-27
 */
@Service
public class FlowService extends BaseService {

	public void add(Flow f) {
		Date now = new Date();
		f.setCrtDate(now);
		f.setModDate(now);

		save(f);
	}

	public void del(Long id) {
		delete(Flow.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<Flow> digg() {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Flow.class);
			query.setFilter("hidden == false");
			query.setOrdering("rating desc");
			query.setRange(0, 15);
			Collection<Flow> c = pm.detachCopyAll((Collection<Flow>) query.execute());
			return new ArrayList<Flow>(c);
		} finally {
			pm.close();
		}
	}

	public Flow get(Long id) {
		return get(Flow.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<Flow> getByPack(long packId) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Flow.class);
			query.setFilter("hidden == false && packId == :packId");
			query.setOrdering("crtDate desc");
			query.setRange(0, 15);
			Collection<Flow> c = pm.detachCopyAll((Collection<Flow>) query.execute(packId));
			return new ArrayList<Flow>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Flow> getLattestByUser(String userName, int number) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Flow.class);
			query.setFilter("hidden == false && owner == :owner");
			query.setOrdering("crtDate desc");
			number = (number == 0) ? 15 : number;
			query.setRange(0, number);
			Collection<Flow> c = pm.detachCopyAll((Collection<Flow>) query.execute(userName));
			return new ArrayList<Flow>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Flow> hottest() {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Flow.class);
			query.setFilter("hidden == false");
			query.setOrdering("rating desc");
			query.setRange(0, 15);
			Collection<Flow> c = pm.detachCopyAll((Collection<Flow>) query.execute());
			return new ArrayList<Flow>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Flow> latest() {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Flow.class);
			query.setFilter("hidden == false");
			query.setOrdering("crtDate desc");
			query.setRange(0, 15);
			Collection<Flow> c = pm.detachCopyAll((Collection<Flow>) query.execute());
			return new ArrayList<Flow>(c);
		} finally {
			pm.close();
		}
	}

	public List<Flow> list() {
		return list(Flow.class);
	}
}
